package com.qingcheng.task;

import com.alibaba.fastjson.JSON;
import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.pojo.seckill.SeckillOrder;
import com.qingcheng.util.IdWorker;
import com.qingcheng.util.SeckillStatus;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: LDeng
 * @Date: 2020-07-16 17:19
 */

@Component
public class MultiThreadingCreateOrder {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private IdWorker idWorker;

    @Async
    public void createOrder() {
        try {
            System.out.println("-------------MultiThreadingCreateOrder准备执行异步下单-------------");
            //Thread.sleep(10000);

            //替换测试数据
            SeckillStatus seckillStatus =(SeckillStatus) redisTemplate.boundListOps("SeckillOrderQueue").rightPop();

            //用户抢单数据
            String username = seckillStatus.getUsername();
            String time = seckillStatus.getTime();
            Long id = seckillStatus.getGoodsId();

            //获取队列中的商品id
            Object sid = redisTemplate.boundListOps("SeckillGoodsCountList_" + id).rightPop();
            // System.out.println(sid);
                if(sid==null){//售罄
                    //清理排队信息
                    System.out.println("看到这个表示售罄");
                    clearQueue(seckillStatus);
                    return;
                }

            //查询商品详情
            SeckillGoods goods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + time).get(id);

            //Thread.sleep(10000);
            System.out.println(username+":"+Thread.currentThread().getId()+"----查询到的商品库存:"+goods.getStockCount());
            if (goods != null && goods.getStockCount() > 0) {
                //创建订单
                SeckillOrder seckillOrder = new SeckillOrder();
                seckillOrder.setId(idWorker.nextId());
                seckillOrder.setSeckillId(id);
                seckillOrder.setMoney(goods.getCostPrice());
                seckillOrder.setUserId(username);
                seckillOrder.setSellerId(goods.getSellerId());
                seckillOrder.setCreateTime(new Date());
                seckillOrder.setStatus("0");

                redisTemplate.boundHashOps("SeckillOrder").put(username, seckillOrder);
                //库存扣减
                Long surplusCount = redisTemplate.boundHashOps("SeckillGoodsCount").increment(goods.getId(), -1);
                goods.setStockCount(surplusCount.intValue());
                //商品库存=0 -> 将数据同步到MySQL, 并清理redis 缓存
                if (surplusCount <= 0) {
                    seckillGoodsMapper.updateByPrimaryKey(goods);
                    redisTemplate.boundHashOps("SeckillGoods_" + time).delete(id);
                } else {
                    redisTemplate.boundHashOps("SeckillGoods_" + time).put(id, goods);
                }

                //变更排队信息
                seckillStatus.setOrderId(seckillOrder.getId());
                seckillStatus.setMoney(seckillOrder.getMoney().floatValue());
                seckillStatus.setStatus(2);//抢单成功， 待支付
                redisTemplate.boundHashOps("UserQueueStatus").put(username,seckillStatus);

                //发送消息
                sendDelayMessage(seckillStatus);

                System.out.println("MultiThreadingCreateOrder中的 OrderID=========>"+seckillStatus.getOrderId());
                System.out.println("-------------10秒后 MultiThreadingCreateOrder下单成功-------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //清理用户排队信息
    private void clearQueue(SeckillStatus seckillStatus) {

        //清理重复的排队标识
        redisTemplate.boundHashOps("UserQueueCount").delete(seckillStatus.getUsername());
        //清理排队存储信息
        redisTemplate.boundHashOps("UserQueueStatus").delete(seckillStatus.getUsername());

    }


    @Autowired
    private  RabbitTemplate rabbitTemplate;


    //延时消息发送
    public void sendDelayMessage(SeckillStatus seckillStatus){
        rabbitTemplate.convertAndSend(
                "exchange.delay.order.begin",
                "delay",
                 JSON.toJSONString(seckillStatus), //发送数据
                 new MessagePostProcessor(){
                     public Message postProcessMessage(Message message) throws AmqpException {
                         message.getMessageProperties().setExpiration(String.valueOf(10000));
                         return message;
                     }
                 });
        System.out.println("消息已经发送到exchange.delay.order.begin.....");
    }
}
